const { login } = require("../controller/user");
const { SuccessModel, ErrorModel } = require("../model/resModel");
const handelUserRouter = (req, res) => {
  const method = req.method;
  const path = req.path;
  if (method === "POST" && path === "/api/user/login") {
    const { userName, userPass } = req.body;
    if(!userName){
      return Promise.resolve(new ErrorModel("用户名不能为空"))
    }
    if(!userPass){
      return Promise.resolve(new ErrorModel("密码不能为空"))
    }
    const result = login(userName, userPass);
    return result.then(res=>{
      if (res) {
        if(res.username){
          const currentTime = (new Date()).getTime()
          req.session.userName = res.username;
          // 相当于 SESSION_DATA[uuid] = res.username; 给每个用户保存了一个变量
        }
        return new SuccessModel("登录成功");
      } else {
        return new ErrorModel("登录失败");
      }
    })
  }
  if (method === "GET" && path === "/api/user/login-test") {
    if(req.session.userName){
      return Promise.resolve(new SuccessModel('已经登录了'))
    }else{
      return Promise.resolve(new ErrorModel('尚未登录'))
    }
  }
};
module.exports = handelUserRouter;
